﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;

namespace Zero.UControl.Base.Helper.Base
{
    internal class GroupCommand : IDrawingCommand
    {
        private readonly Canvas _c;
        private readonly List<UIElement> _items;
        public Canvas GroupContainer { get; }

        public GroupCommand(Canvas c, List<UIElement> items)
        {
            _c = c; _items = items;
            GroupContainer = new Canvas
            {
                Background = Brushes.Transparent
            };
        }
        public void Execute()
        {
            if (_c.Children.Contains(GroupContainer)) return;
            // 计算包围盒
            double left = _items.Min(i => Canvas.GetLeft(i)), top = _items.Min(i => Canvas.GetTop(i));
            foreach (var el in _items)
            {
                _c.Children.Remove(el);
                GroupContainer.Children.Add(el);
                Canvas.SetLeft(el, Canvas.GetLeft(el) - left);
                Canvas.SetTop(el, Canvas.GetTop(el) - top);
            }
            Canvas.SetLeft(GroupContainer, left);
            Canvas.SetTop(GroupContainer, top);
            _c.Children.Add(GroupContainer);
        }
        public void UnExecute()
        {
            if (!_c.Children.Contains(GroupContainer)) return;
            double gx = Canvas.GetLeft(GroupContainer), gy = Canvas.GetTop(GroupContainer);
            foreach (var el in _items)
            {
                GroupContainer.Children.Remove(el);
                _c.Children.Add(el);
                Canvas.SetLeft(el, gx + Canvas.GetLeft(el));
                Canvas.SetTop(el, gy + Canvas.GetTop(el));
            }
            _c.Children.Remove(GroupContainer);
        }
    }
}
